package com.gem.shop.dao.impl;

import com.gem.shop.dao.CommodityDao;
import com.gem.shop.entity.Commodity;
import com.gem.shop.util.HibernateTemplate;
import org.hibernate.Hibernate;

import java.util.List;

/**
 * @author zhang
 * @date 2020/9/17 11:19
 */
public class CommodityDaoImpl implements CommodityDao {

    @Override
    public List<Commodity> selectAllCommoditys() {
        return (List<Commodity>) HibernateTemplate.execute(ses -> ses.createQuery("from Commodity").list());
    }

    @Override
    public List<Commodity> selectCommoditysByType(Integer type) {
        return (List<Commodity>) HibernateTemplate.execute(ses -> ses.createQuery("from Commodity where type = :type").setParameter("type",type).list());
    }

    @Override
    public void insertCommodity(Commodity commodity) {
        HibernateTemplate.execute(ses -> ses.save(commodity));
    }

    @Override
    public List<Commodity> selectCommoditysByPagesAndType(int pageNow,int pageSize,String type) {
        return (List<Commodity>) HibernateTemplate.execute(ses -> ses.createQuery("from Commodity where type = :type").setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize).setParameter("type",type).list());
    }

    @Override
    public List<Commodity> selectCommoditysByPagesAndName(int pageNow, int pageSize, String name) {
        return (List<Commodity>) HibernateTemplate.execute(ses -> ses.createQuery("from Commodity where name like :name").setParameter("name","%" + name + "%").setFirstResult((pageNow - 1) * pageSize).setMaxResults(pageSize).list());
    }

    @Override
    public Long selectCommoditysByPagesAndNameCount(String name) {
        return (Long) HibernateTemplate.execute(ses -> ses.createQuery("select count(*) from Commodity where name like :name").setParameter("name","%" + name + "%").uniqueResult());
    }

    @Override
    public Long selectCommoditysByTypeCount(String type) {
        return (Long) HibernateTemplate.execute(ses -> ses.createQuery("select count(*) from Commodity where type = :type").setParameter("type",type).uniqueResult());
    }

    @Override
    public List<String> selectAllType() {
        return (List<String>) HibernateTemplate.execute(ses -> ses.createQuery("select distinct type from Commodity").list());
    }

    @Override
    public Commodity selectCommodityById(int id) {
        return (Commodity) HibernateTemplate.execute(ses -> ses.get(Commodity.class,id));
    }

    @Override
    public List<Commodity> selectCommodityByNameAndType(String name, String type) {
        return (List<Commodity>) HibernateTemplate.execute(ses -> ses.
                createQuery("from Commodity where type = :type and name like :name")
                .setParameter("type",type).setParameter("name","%"+ (name == null ? "" : name) + "%")
                .list());
    }
}
